package com.aloaproject.ciquta;

import java.lang.reflect.Method;

/**
 * Utility class to discover properties of classes through reflection.
 * @author Daniele Demichelis
 */
final public class ClassReflectionWrapper {

    private Class clazz;

    public ClassReflectionWrapper(Class clazz) {
        this.clazz = clazz;
    }

    final boolean hasReadableProperty(final String property) {

    	//.isEmpty() does not seems java 1.5
        //if(property == null || property.trim().isEmpty()){
    	if(property == null || property.trim().length()==0){
            throw new IllegalArgumentException("Property has an illegal value.");
        }

        if(property.contains(".")){
            //recursion
            boolean result = false;
            String simpleProperty = property.substring(0, property.indexOf("."));
            String restProperty = property.substring(property.indexOf(".")+1);
            try {
                ClassReflectionWrapper sub = new ClassReflectionWrapper(getGetterMethod(simpleProperty).getReturnType());
                result = sub.hasReadableProperty(restProperty);
            } catch (NoSuchMethodException ex) {
                result = false;
            }
            return result;
        }else{
            //base
            boolean result = false;
            try {
                Method getterMethod = getGetterMethod(property);
                result = getterMethod != null;
            } catch (NoSuchMethodException ex) {
                //no method with the given name
                result = false;
            }
            return result;
        }


    }

    Method getGetterMethod(String property) throws NoSuchMethodException{
        return clazz.getMethod(buildGetterNameForProperty(property), (Class<?>[]) null);
    }

    private String buildGetterNameForProperty(String property){
        return new StringBuffer()
            .append("get")
            .append(property.substring(0, 1).toUpperCase())
            .append(property.substring(1))
            .toString();
    }

}
